package org.zk.service.impl;

import org.zk.dao.*;
import org.zk.dto.CommentsAndInfosDto;
import org.zk.dto.PreOrders;
import org.zk.dto.SixGoodsByCatelogDto;
import org.zk.entity.*;
import org.zk.service.GoodsService;
import org.zk.util.UtilDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    CatelogMapper catelogMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    ImageMapper imageMapper;
    @Autowired
    CommentsMapper commentsMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PurseMapper purseMapper;
    @Autowired
    OrdersMapper ordersMapper;


    @Override
    public List<SixGoodsByCatelogDto> getSixGoodsByCatelog() {

        List<SixGoodsByCatelogDto> targetDtoList = new ArrayList<>();
        List<Catelog> allCatelog = catelogMapper.selectAllCatelog();

        for (Catelog catelog : allCatelog) {

            SixGoodsByCatelogDto dto = new SixGoodsByCatelogDto();
            dto.setCatename(catelog.getName());

            List<Goods> goodsByCatelog = goodsMapper.selectSixGoodsByCatelog(catelog.getId());

            for (Goods goods : goodsByCatelog) {


                GoodsExt2 goodsExt = new GoodsExt2(goods);

                List<Image> imageList = imageMapper.selectByGoodsPrimaryKey(goods.getId());
                if (imageList == null) {
                    goodsExt.setImgUrl(null);
                }
                goodsExt.setImgUrl(imageList.get(0) != null ? imageList.get(0).getImgUrl() : null);

                dto.getGoodses().add(goodsExt);
            }
            targetDtoList.add(dto);

        }
        return targetDtoList;
    }

    @Override
    public List<GoodsExt2> getGoodsesById(Integer cateId, Integer limit, Integer page) {

        List<GoodsExt2> goodsExtList = new ArrayList<>();
//        System.out.println("cateId"+cateId);
        Integer countByCateId = goodsMapper.getCountByCateId(cateId);
//        System.out.println("pageCount:"+countByCateId);
        if (countByCateId <= 0) {
            return null;
        }
        //通过总数 和 每页数目 计算出页数
        Integer pageCount = 0;
        if (limit > 0) {

            if (countByCateId % limit == 0) {
                pageCount = countByCateId / limit;
            } else {
                pageCount = countByCateId / limit + 1;
            }
        }
        //获取的页码正常
        if (page >= 0 && page <= pageCount) {
            List<Goods> goodsList = goodsMapper.selectGoodsByCatelog(cateId, (page - 1) * limit, limit);
            //遍历直接得到的Goods 对每个商品进行扩展
            for (Goods goods : goodsList) {
                System.out.println(goods);
                GoodsExt2 goodsExt2 = new GoodsExt2(goods);

                List<Image> images = imageMapper.selectByGoodsPrimaryKey(goods.getId());
                if (images != null) {
                    String imgUrl = images.get(0).getImgUrl();
                    goodsExt2.setImgUrl(imgUrl);
                }
                goodsExtList.add(goodsExt2);
            }
            return goodsExtList;
        }
        return null;
    }

    @Override
    public Integer getGoodsesCountById(Integer cateId) {
        return goodsMapper.getCountByCateId(cateId);
    }

    @Override
    public CommentsAndInfosDto getGoodsAndComAndInfoByGid(Integer goodsId) {


        Goods goods1 = goodsMapper.selectGoodsByGidWithoutStatus(goodsId);
        if(goods1 == null){
            return null;
        }
        CommentsAndInfosDto dto = new CommentsAndInfosDto();

        //根据商品id查询 商品信息、售卖人信息、商品评论
        List<Comments> commentsList = commentsMapper.selectCommentsByGoodsId(goodsId);
        //一件商品可能有多条评论 一对多  封装带用户名的评论
        List<CommentsWithUser> commentsWithUserList = new ArrayList<>();

        if (commentsList != null) {

            for (Comments comment : commentsList) {

                CommentsWithUser commentUser = new CommentsWithUser();
                commentUser.setContent(comment.getContent());
                commentUser.setCreate_at(comment.getCreateAt());
                User userOfComment = userMapper.selectUserByUid(comment.getUserId());
                commentUser.setUser(userOfComment.getUsername());

                commentsWithUserList.add(commentUser);
            }
        }
        dto.setComments(commentsWithUserList);
        //一件商品只能所属一个用户 一对一
        User seller = null;
        Goods goods = goodsMapper.selectGoodsByGidWithoutStatus(goodsId);
        if (goods != null) {
            goods.setId(goodsId);
            Integer userId = goods.getUserId();
            seller = userMapper.selectUserByUidPart(userId);

//          构造商品信息
            GoodsExt2 goodsExt2 = new GoodsExt2(goods);
            List<Image> images = imageMapper.selectByGoodsPrimaryKey(goodsId);

            if (images != null && images.size() > 0) {
                System.out.println("image:"+images.get(0).getImgUrl());
                goodsExt2.setImgUrl(images.get(0).getImgUrl());
            }else{
                goodsExt2.setImgUrl("");
            }

            Catelog catelog = catelogMapper.selectCatelogById(goods.getCatelogId());

            goodsExt2.setCatelog(catelog == null ? "" : catelog.getName());


            dto.setGoods(goodsExt2);
        }
        dto.setUserInfo(seller);
        return dto;
    }

    @Override
    public Integer addGoods(Goods good) {
        return goodsMapper.insertGoods(good);
    }

    @Override
    public List<Goods> getFocusGoodsesByUid(Integer uid) {
        return goodsMapper.selectFocusGoodsesByUid(uid);
    }



    @Override
    public List<GoodsExt2> searchGoods(String goodsInfo, Integer limit, Integer page) {


        ArrayList<GoodsExt2> goodsExt2List = new ArrayList<>();
//      分页步骤
//      1. 获得总数目
        Integer count = goodsMapper.selectCountGoodsByNameOrDesc(goodsInfo);
        if (count < 1) {
            return null;
        }
//      2.根据limit值 算出总页数
        Integer pageCount = 0;
        if (limit > 0) {

            if (count % limit == 0) {
                pageCount = count / limit;
            } else {
                pageCount = count / limit + 1;
            }
        }
        if (page >= 0 && page <= pageCount) {
//          3. 根据页数和每页的值 构造sql语句
//            List<Goods> goodsList = goodsMapper.selectGoodsByCatelog(cateId, (page - 1) * limit, limit);
            List<Goods> goodsList = goodsMapper.selectGoodsByNameOrDesc(goodsInfo, (page - 1) * limit, limit);
            if (goodsList != null) {
                //遍历直接得到的Goods 对每个商品进行扩展
                for (Goods goods : goodsList) {
                    GoodsExt2 goodsExt2 = new GoodsExt2();
                    goodsExt2.setId(goods.getId());

                    List<Image> images = imageMapper.selectByGoodsPrimaryKey(goods.getId());
                    if (images != null) {
                        String imgUrl = images.get(0).getImgUrl();
                        goodsExt2.setImgUrl(imgUrl);
                    }
                    goodsExt2.setName(goods.getName());
                    goodsExt2.setPrice(goods.getPrice());
                    goodsExt2.setStartTime(goods.getStartTime());

                    goodsExt2List.add(goodsExt2);
                }
            }
        }
        //如果没有被添加元素则返回null 否则返回它的值
        return goodsExt2List.size() == 0 ? null : goodsExt2List;
    }

    @Override
    public List<GoodsExt2> getGoodsesByUid(Integer userId) {

        List<Goods> goodsList = goodsMapper.selectGoodsesByUid(userId);
        List<GoodsExt2> targetgoodeList = new ArrayList<>();
        for (Goods goods : goodsList) {
            GoodsExt2 goodsExt2 = new GoodsExt2();
            goodsExt2.setId(goods.getId());
            goodsExt2.setName(goods.getName());
            goodsExt2.setDescrible(goods.getDescrible());

//            System.out.println(goods.getDescrible());
            List<Image> images = imageMapper.selectByGoodsPrimaryKey(goods.getId());
            if (images != null) {
                String imgUrl = images.get(0).getImgUrl();
                goodsExt2.setImgUrl(imgUrl);
            }
            goodsExt2.setStartTime(goods.getStartTime());
            goodsExt2.setEndTime(goods.getEndTime() == null ? "" : goods.getEndTime());
//            System.out.println(goods.getEndTime());
            targetgoodeList.add(goodsExt2);
        }
        return targetgoodeList;
    }

    @Override
    public Goods getGoodsByPrimaryKey(Integer goodsId) {

        return goodsMapper.selectGoodsByGid(goodsId);
    }

    @Override
    public Goods getGoodsByPrimaryKeyWithoutStatus(Integer goodsId) {
        return goodsMapper.selectGoodsByGidWithoutStatus(goodsId);
    }

    @Override
    public Integer withdrawGoods(Integer goodsId) {
        String endTime = UtilDate.getCurrentDateStrAll();
        return goodsMapper.updateEndTimeAndStatusByGid(goodsId, endTime);
    }

    @Override
    public PreOrders getPreOrders(Integer uid, Integer goodsId) {

//        (int)((Math.random()*9+1)*1000)  四随机数

        String orderNumStr = String.valueOf(uid) + String.valueOf(goodsId) + String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        Long orderNum = Long.valueOf(orderNumStr);

        Purse purse = purseMapper.selectPurseByUid(uid);
        Goods goods = goodsMapper.selectGoodsByGid(goodsId);

        if (purse != null && goods != null) {

            PreOrders preOrders = new PreOrders(goods);
            preOrders.setBalance(purse.getBalance());
            preOrders.setOrderNum(orderNum);
            List<Image> images = imageMapper.selectByGoodsPrimaryKey(goodsId);
            if (images != null) {
                String imgUrl = images.get(0) != null ? images.get(0).getImgUrl() : null;
                preOrders.setImgUrl(imgUrl);
            }
            return preOrders;

        }

        return null;
    }

    @Override
    public Integer getCountGoodsByNameOrDesc(String goodsInfo) {
        return goodsMapper.selectCountGoodsByNameOrDesc(goodsInfo);
    }

    @Override
    public Integer addOrders(Orders orders) {

        orders.setOrderState(1);
        orders.setOrderDate(UtilDate.getCurrentDateStrAll());
        Integer goodsId = orders.getGoodsId();
        Goods goods = goodsMapper.selectGoodsByGid(goodsId);
        if (goods != null) {
            orders.setOrderPrice(goods.getPrice());
        }
        Integer rst = ordersMapper.insertOrders(orders);
        if (rst > 0) {
            return 1;
        }
        return 0;
    }

    @Override
    public Integer rmGoods(Integer goodsId) {

        Integer rst = goodsMapper.delGoods(goodsId);
        if(rst > 0){
            return 1;
        }

        return 0;
    }
}
